package com.zy.view.diy;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

import com.zy.utils.CanvasUtils;
import com.zy.utils.DataBuildUtils;
import com.zy.utils.data.Point;
import com.zy.zlog.ZLog;

import java.util.ArrayList;
import java.util.List;

//拖动
public class DIYCanvasView004 extends View {


    public DIYCanvasView004(Context context) {
        super(context);
        init(context);
    }


    public DIYCanvasView004(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DIYCanvasView004(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public DIYCanvasView004(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    Paint textPaint;
    Paint indexPaint;
    Paint assistLinePaint;

    private void init(Context context) {

        textPaint = new Paint();
        //设置文本大小
        textPaint.setTextSize(72);
        textPaint.setAntiAlias(true);
        //设置文本对齐方式
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.RED);

        indexPaint = new Paint();
        //设置文本大小
        indexPaint.setTextSize(36);
        indexPaint.setStyle(Paint.Style.STROKE);
        indexPaint.setStrokeWidth(5);
        //设置文本对齐方式
        indexPaint.setTextAlign(Paint.Align.CENTER);
        indexPaint.setColor(Color.BLUE);


        assistLinePaint = new Paint();
        assistLinePaint.setColor(Color.GRAY);
        DashPathEffect effects = new DashPathEffect(new float[]{20, 10, 20, 10}, 10);
        assistLinePaint.setPathEffect(effects);


    }

    private List<Point> pointList = new ArrayList<>();

    int D = 0;

    /**
     * @param d    辅助格子大小
     * @param x    x位置
     * @param y    y位置
     * @param per  每个node大小 一旦小于 d/2
     * @param size 数据
     */
    public void create(int d, int x, int y, int per, int size) {
        D = d;
        int[] array = DataBuildUtils.getRandomSortArray(size, size);
        pointList = CanvasUtils.buildFirst(x * d, y * d, d, array, per, Point.Type.DEFAULT);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (D > 0) {
            CanvasUtils.drawAssistLineV2(canvas, assistLinePaint, D);
            //辅助线
        }

        for (Point point : pointList) {
            point.draw(canvas, textPaint, indexPaint);
        }
    }

    //保存node存在的位置
    //二维数组 [0行或者 0列 不保存数据]
    //node移动后 按照就近原则复原


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        ZLog.INSTANCE.d("DIYCanvasView004", "onTouchEvent:" + MotionEvent.actionToString(event.getAction()));
        //return super.onTouchEvent(event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //找到当前位置的node，记录下来 (有可能没有node 不做任何事)
                curPoint = findNode(event);
                if (curPoint == null) {
                    return false;
                }
                downX = x;
                downY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                //移动node
                curPoint.updateOff(x - downX, y - downY);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                //给node找到新的位置
                //新位置已经存在
                //新位置为kong
                //动画
                moveUp(event);
                break;
        }
        return true;
    }

    Point curPoint = null;
    int downX = 0;
    int downY = 0;

    private Point findNode(MotionEvent event) {
        for (Point point : pointList) {
            if (point.isRange(event)) {
                return point;
            }
        }
        return null;
    }

    public void moveUp(MotionEvent event) {
        if (curPoint == null) {
            return;
        }
        int curX = (int) event.getX();
        int curY = (int) event.getY();


        //计算就近位置
        int targetX = (curX / D * D);

        if (curX - targetX > (D >> 1)) {
            targetX += D;
        }

        int targetY = (curY / D * D);
        if (curY - targetY > (D >> 1)) {
            targetY += D;
        }

        ZLog.INSTANCE.d("DIYCanvasView004", "moveUp:" + curX + " " + targetX + " " + curY + " " + targetY);

        curPoint.updateOff(curX - targetX, curY - targetY);
        curPoint.setPercentage(1f);
        curPoint.setPoint(targetX, targetY);


        ValueAnimator mAnimator = ValueAnimator.ofFloat(1, 0);
        mAnimator.setDuration(100);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                //时间流,必须是线性的
                float percentage = (float) animation.getAnimatedValue();
                curPoint.setPercentage(percentage);
                invalidate();
            }
        });


        mAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation, boolean isReverse) {
                super.onAnimationEnd(animation, isReverse);
                curPoint.resetOff();
                curPoint = null;
            }
        });
        mAnimator.start();
    }
}
